<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8" isELIgnored="false"%>
<%@ include file="/WEB-INF/views/shared/taglib.jsp"%>
<%
	request.setAttribute("modelConfigPath", "billing");
%>
<%@ include file="/WEB-INF/views/shared/master/contentHeader.jsp"%>
<style >
	#outStockInfoCopy{display:none}
	td input{height:21px; width:98%;border:none;}
	td{height:21px;padding: 2px 2px !important;text-align:center }
	#area{
		height:344px;
		overflow-y:auto; 
		overflow-x:hidden; 
	}
</style>
<t:panel cssClass="panel-flat form-detailed" customBody="true" customHead="true">
	<div class="detailed-navbar-content panel-body">
		<t:form modelAttribute="billing" action="/billing/returnOfCargo/save" method="post" cssClass="form-horizontal">
			<div class="hide">
				 <t:hidden path="billingId"/>
 				 <t:hidden path="deleteMark"/>	
 				 <t:hidden path="createUserName"/>
		 		 <t:hidden path="createUserId"/>
		 		 <t:hidden path="createDate"/>
		 		 <t:hidden path="shopId"/>
		 		
			</div>
            <t:formgroup>
            	<t:label path="billingNo" cssClass="col-sm-1 col-xs-1" />
		        <t:input readonly="true" path="billingNo" colClass="col-sm-2 col-xs-2" />
                <t:label path="customerId" cssClass="col-sm-1 col-xs-1" />
                <t:select2 path="customerId" placeholder="请填写客户" allowClear="true" colClass="col-sm-2 col-xs-2"></t:select2>
            	<t:label path="deliveryDate" cssClass="col-sm-1 col-xs-1" />
                <t:date  path="deliveryDate" colClass="col-sm-2 col-xs-2"></t:date>
                <t:label path="businessId" cssClass="col-sm-1 col-xs-1" />
                <t:select2 path="businessId" placeholder="业务员" allowClear="true" colClass="col-sm-2 col-xs-2"></t:select2>
            </t:formgroup>
            <t:formgroup>
            	<t:label path="billingMoney" cssClass="col-sm-1 col-xs-1" />
				<t:input path="billingMoney" colClass="col-sm-2 col-xs-2" />
                <t:label path="discount" cssClass="col-sm-1 col-xs-1" />
				<t:input path="discount" colClass="col-sm-2 col-xs-2" />
            	<t:label path="comment" cssClass="col-sm-1 col-xs-1" />
				<t:textarea  path="comment" colClass="col-md-5"/> 
			</t:formgroup>
            <div id="area">
            <table  class="cntable table table-bordered dataTable table-billing">
	            <thead>
	            	<tr class="success">
		            	<th style="width:80px">序号</th>
		            	<th style="width:100px">操作</th>
		            	<th style="width:150px">商品编码</th>
		            	<th style="width:200px">商品名称</th>
		            	<th style="width:150px">规格</th>
		            	<th style="width:100px">单位</th>
		            	<th style="width:100px">数量</th>
		            	<th style="width:100px">单价</th>
		            	<th>小计</th>
	            	</tr>
	            </thead>
	            
	            <tbody onclick="checkCustomer()" id="outStockInfo">
					<tr id="outStockCollocation_0" name="outStockCollocation">
						<td style="display:none"><input id="collocationId_0" name="collocationId" type="text" value=""/></td>
						<td style="display:none"><input id="cargoId_0" name="cargoId" type="text" value=""/></td>
						<td class="cargoType" style="display:none"><input id="cargoType_0" name="cargoType" type="text" value=""/></td>
						<td name="index"></td>
						<td id="logo" >
			            	<div class="col-md-6 col-sm-6" onclick="addData()" ><i class="fa fa-plus-square"></i></div>
			            	<div class="col-md-6 col-sm-6" onclick="deleteData('outStockCollocation_0')"><i class="fa fa-minus-square"></i></div>
		            	</td>
						
		            	<td colspan="2"><select style="ime-mode:disabled;" id="cargoNo_0" name="cargoNo" type="text"  value=""><option value=""></option></select></td>
		           
		            	<td style="display:none;"><input  style="ime-mode:disabled;" readonly="true" id="cargoNoShow_0" name="cargoNoShow" type="text" value=""/></td>
		            	<td style="display:none;"><input  style="ime-mode:disabled" readonly="true" id="cargoName_0" name="cargoName" type="text" value=""/></td>
		            	<td><input style="ime-mode:disabled" readonly="true" id="propertyName_0" name="propertyName" type="text" value=""/></td>
						<td >
		            		<select placeholder="供应商" style="ime-mode:disabled;" id="unit_0" name="unit" type="text" value=""></select>
		            	</td>								
						<td><input style="ime-mode:disabled" class="form-control  "  onkeyup="return ValidateNumber(this,value)" id="collocationNum_0"  name="collocationNum" type="text" value=""/></td>
						<td><input onchange="change(this)" style="ime-mode:disabled" class="form-control  " onkeyup="return ValidateNumber(this,value)" id="realPrice_0" name="realPrice" type="text" value=""/></td>
						<td><input style="ime-mode:disabled" class="form-control  " id="subtotal_0" name="subtotal" type="text" value=""/></td>
					</tr>
					<c:set var="sequence"  value="0"/>
				</tbody>
            </table>
			</div>
		</t:form>
	</div>
	<t:panelFoot headingBtnCssClass="heading-btn pull-right-important">
		<t:button icon="icon-floppy-disk" onclick="saveData()" laddaType="progress" cssClass="btn-info" csize="sm">保存</t:button>
	</t:panelFoot>
</t:panel>
	
<table id="outStockInfoCopy">
	<tbody id="outStockInfoCopyBody">
		<tr id="outStockCollocation_temp"  name="outStockCollocation">
			<td style="display:none"><input id="collocationId_temp" name="collocationId" type="text" value=""/></td>
			<td style="display:none"><input id="cargoId_temp" name="cargoId" type="text" value=""/></td>
			<td class="cargoType" style="display:none"><input id="cargoType_temp" name="cargoType" type="text" value=""/></td>
			<td name="index"></td>
			<td id="logo" >
		          	<div class="col-md-6 col-sm-6" onclick="addData()" ><i class="fa fa-plus-square"></i></div>
		          	<div class="col-md-6 col-sm-6" onclick="deleteData('outStockCollocation_temp')"><i class="fa fa-minus-square"></i></div>
		     </td>
								
         	<td colspan="2"><select style="ime-mode:disabled;" id="cargoNo_temp" name="cargoNo" type="text" value=""><option value=""></option></select></td>
         	<td style="display:none;"><input style="ime-mode:disabled;" readonly="true" id="cargoNoShow_temp" name="cargoNoShow" type="text" value=""/></td>
         	<td style="display:none;"><input style="ime-mode:disabled" readonly="true" id="cargoName_temp" name="cargoName" type="text" value=""/></td>
         	<td><input style="ime-mode:disabled" readonly="true" id="propertyName_temp" name="propertyName" type="text" value=""/></td>
			<td >
				<select placeholder="供应商" style="ime-mode:disabled;"id="unit_temp" name="unit" type="text" value=""></select>
			</td>	
			<td><input style="ime-mode:disabled" class="form-control  "  onkeyup="return ValidateNumber(this,value)" id="collocationNum_temp"  name="collocationNum" type="text" value=""/></td>
			<td><input onchange="change(this)" style="ime-mode:disabled" class="form-control  "  onkeyup="return ValidateNumber(this,value)" id="realPrice_temp" name="realPrice" type="text" value=""/></td>
			<td><input style="ime-mode:disabled" class="form-control  " id="subtotal_temp" name="subtotal" type="text" value=""/></td>
		</tr>
	</tbody>
</table>
<script type="text/javascript">

$(function(){
	loadStockInfo();
	outStockInfo = $("#outStockInfoCopyBody").html();

	$('#discount').bind('input propertychange', function() {
		var discount = parseFloat($(this).val());
		if(isNaN(discount)){
			discount = 0;
			$(this).val(0);
		}else if(discount>10){
			discount = 10;
			$(this).val(10);
		}
		updateBillingMoney();
	});
	

	stocksShow(0);

	indexChange();
	
	iframeLazyOpen();
	tabpaneResize();

})

var stocksInfoJson=[];
var stuffData=[];
var unitInfo=[];
var unitInfoForChange=[];
var changeNum=0;
function loadStockInfo(){
	$("#customerId").change(function(){
		var collocationIds=[];
		var showConfirm=false;
		$("input[name='collocationId']").each(function(){
			collocationIds.push({
				id:$(this).val(),
				text:$(this).val()
			})
		});

		for(var i=0;i<collocationIds.length;i++){
			if(collocationIds[i].id!=""){
				showConfirm=true
			}
		}
		
		changeNum++;
		if(showConfirm){
			if(changeNum>1){
				confirm("是否确认修改客户？修改后，将清除已选择数据。",function(result){
	    			if(result){
	    				stocksShow(0);
	    				deleteAll();
	    			}else{
	    				return;
	    			}
	    		});
			}else{
				stocksShow(0);
			}
		}else{
			stocksShow(0);
		}
	})
		
}

function getStockInfo(findInfo){
	unitInfo=[];
	stocksInfoJson=[]
	var customerId=$("#customerId").find("option:selected").val();
	var url =$.getVirtualPath()+"/stock/stock/getStockInfo";
    $.ajax({
        type: 'get',
        dataType: "json",
        url: url,
        data: "searchKey="+findInfo+"&customerId="+customerId,
        async: false,
        success: function (result) {
        	if(result!=null){
    			stocksInfoJson =result.data;
    		
    		}
       	}
    });
    
} 
function deleteAll(){
	$("tr[name='outStockCollocation']").each(function(){
		if($(this).attr("id")!="outStockCollocation_temp"){
			$(this).remove();
			updateBillingMoney();
			indexChange();
		}
	});
	num=0;
	newOutStockInfo=outStockInfo.replace(/1/g,num+1);
	newOutStockInfo=newOutStockInfo.replace(/temp/g,num);
	
	$("#outStockInfo").append(newOutStockInfo);
	stocksShow(num);
	indexChange();
	
}
var unitListForEdit=[];
function stocksShow(showNum){
	var customerId=$("#customerId").find("option:selected").val();
	unitInfo=[];
	var select2=$('#unit_'+showNum).select2({placeholder:"请选择单位",allowClear: true ,data : unitInfo});
	var select=$('#cargoNo_'+showNum).select2({placeholder:"请选择货物信息",allowClear: true ,data : stuffData});
	if(!$.isNull(customerId)){
		select=$('#cargoNo_'+showNum).select2({placeholder:"请选择货物信息",allowClear: true ,data : stuffData,query: function (query) {
	        
	        var data = {results: []};
	        if(query.term!=null){
	        	getStockInfo(query.term);
	        }else{
	        	getStockInfo("");
	        }
	        
			stocksInfoJson.forEach(function(element,index){
				 if(!$.isNull(element.propertyNameTwo)){
					 data.results.push({
						id:element.collocationId,
						text:element.cargoNo+" "+element.cargoName+" "+"【"+element.propertyNameOne+"*"+element.propertyNameTwo+"】",
	    				})
				 }else{
					 data.results.push({
						id:element.collocationId,
						text:element.cargoNo+" "+element.cargoName+" "+"【"+element.propertyNameOne+"】",
	    				})
				 }
					
			});
	        
	        query.callback(data);
	    }});
	}
	select.change(function(){
		unitInfoForChange=[];
		var collocationId = $('#cargoNo_'+showNum).val();
		var repetitionNum = 0;
		$("select[name='cargoNo']").each(function(){
			if($(this).val()!=null&&$(this).val()!=""){
				if($(this).val()==collocationId){
					repetitionNum++;
				}
			}
			
		});
		stocksInfoJson.forEach(function(element,index){
			if(element.collocationId==collocationId){
				console.log(element.cargoType)
				if(!$.isNull(element.unit)){
					unitInfo.push({
						id:element.unit,
						text:element.unit,
						ratio:"1",
						mark:element.collocationId
					})
				}
				
				if(!$.isNull(element.viceFirstUnit)){
					unitInfo.push({
						id:element.viceFirstUnit,
						text:element.viceFirstUnit+"（"+element.firstRatio+"）",
						ratio:element.firstRatio,
						mark:element.collocationId
						
					})
				}
				if(!$.isNull(element.viceSecondUnit)){
					unitInfo.push({
						id:element.viceSecondUnit,
						text:element.viceSecondUnit+"（"+element.secondRatio+"）",
						ratio:element.secondRatio,
						mark:element.collocationId
					})
				}
				unitInfoForChange=unitInfo;
				unitListForEdit.push(unitInfoForChange)
				$('#cargoId_'+showNum).val(element.cargoId);
				$('#collocationId_'+showNum).val(element.collocationId);
				$('#cargoNoShow_'+showNum).val(element.cargoNo);
				$('#cargoType_'+showNum).val(element.cargoType);
				$('#cargoName_'+showNum).val(element.cargoName);
				$('#unit_'+showNum).val(element.unit);
				if(!$.isNull(element.propertyNameTwo)){
					$('#propertyName_'+showNum).val(element.propertyNameOne + "/" + element.propertyNameTwo);

				}else{
					$('#propertyName_'+showNum).val(element.propertyNameOne);

				}
				$('#collocationNum_'+showNum).val(1);
				if(!$.isNull(element.sellingPrice)){
					$('#realPrice_'+showNum).val(element.sellingPrice);
					$('#subtotal_'+showNum).val(element.sellingPrice*1);
				}else{
					$('#realPrice_'+showNum).val(element.salePrice);
					$('#subtotal_'+showNum).val(element.salePrice*1);
				}
				
				
				select2=$('#unit_'+showNum).select2({placeholder:"请选择单位",allowClear: true ,data : unitInfo});
				select2.change(function (){
					var unit=$(this).val();
					
					if(unitListForEdit.length>0){
						for(var i=0;i<unitListForEdit.length;i++){
							for(var j=0;j<unitListForEdit[i].length;j++){
								if(unitListForEdit[i][j].mark==collocationId){
									if(unitListForEdit[i][j].id==unit){
										var count=$('#collocationNum_'+showNum).val();
										if(!$.isNull(element.sellingPrice)){
											$('#realPrice_'+showNum).val(element.sellingPrice*unitListForEdit[i][j].ratio);
											$('#subtotal_'+showNum).val(element.sellingPrice*unitListForEdit[i][j].ratio*count);
										}else{
											$('#realPrice_'+showNum).val(element.salePrice*unitListForEdit[i][j].ratio);
											$('#subtotal_'+showNum).val(element.salePrice*unitListForEdit[i][j].ratio*count);
										}
																					
									}
								}
							}
						}
						
					}
					updateBillingMoney();
					//updateNumSubtotal();
				})
			}
		});
		var cargoType=$('#cargoType_'+showNum).val()
		
		
		if(cargoType!="库存商品"){
			
			$('#realPrice_'+showNum).css("color","red")
			$('#collocationNum_'+showNum).css("color","red");
			$('#subtotal_'+showNum).css("color","red");
		}
		$("#cargoNoShow_"+showNum).parent().css("display","");
		$("#cargoName_"+showNum).parent().css("display","");
		$("#cargoNo_"+showNum).parent().css("display","none");
		updateBillingMoney();
		
		addNewRow();
	});
	updateSubtotal(showNum);
}


function addNewRow(){
	var isAllow=0;
	var collocationIds=[];
	$("input[name='collocationId']").each(function(){
		collocationIds.push({
			id:$(this).val(),
			text:$(this).val()
		})
	});

	for(var i=0;i<collocationIds.length;i++){
		if(collocationIds[i].id==""){
			isAllow++;
			console.log(isAllow);
		}
	}
	if(isAllow<2){
		addData();
	}
	
}

function change(element){
	var e=element.value
	if($(element).parent().siblings(".cargoType").find("input").val()!="库存商品"){
		$(element).val(-e)
	}
	
}

function updateSubtotal(showNum){
	$('#collocationNum_'+showNum).bind('input propertychange', function() {
		var count = parseFloat($(this).val());
		
		if(isNaN(count)){
			count = 0;
			$(this).val(0);
		}else{
			var numValue = $(this).val();
			if(numValue.length>1){
				if(numValue.substring(1,2)!="."){
					if(numValue.substring(0,1)=='0'){
						$(this).val(parseFloat(numValue.substring(1,numValue.length)));
					}
				}

			}
		}
		var price = $('#realPrice_'+showNum).val();
		$('#subtotal_'+showNum).val(price*count);
		updateBillingMoney();
	});
	$('#realPrice_'+showNum).bind('input propertychange', function() {
		var price = parseFloat($(this).val());

		if(isNaN(price)){
			price = 0;
			$(this).val(0);
		}else{
			var numValue = $(this).val();
			if(numValue.length>1){
				if(numValue.substring(1,2)!="."){
					if(numValue.substring(0,1)=='0'){
						$(this).val(parseFloat(numValue.substring(1,numValue.length)));
					}
				}

			}
		}
		var count = $('#collocationNum_'+showNum).val();
		if($(this).parent().siblings(".cargoType").find("input").val()!="库存商品"){
			$(this).val(price)
			$('#subtotal_'+showNum).val(-price*count);
			updateBillingMoney();
		}else{
			$('#subtotal_'+showNum).val(price*count);
			updateBillingMoney();
		}
		
	});
	$('#collocationNum_'+showNum).focus();
}

function updateBillingMoney(){
	var billingMoney = 0;
	var discount = $("#discount").val();
	if(discount == "" || discount == null || discount == undefined || discount==0){
		$("input[name='subtotal']").each(function(){
			if($(this).val()!=null && $(this).val() != ""){
				billingMoney+= parseFloat($(this).val());
			}
							
		});

		$("#billingMoney").val(billingMoney);
    }else{
    	
    	$("input[name='subtotal']").each(function(){
    		if($(this).val()!=null && $(this).val() != ""){
				billingMoney+= parseFloat($(this).val());
			}			
		});
    	billingMoney=billingMoney*(discount/10);
		$("#billingMoney").val(billingMoney);
    }
}

var outStockInfo;
var newOutStockInfo;
var num=0;
function addData(){
	num++;
	
	newOutStockInfo=outStockInfo.replace(/1/g,num+1);
	newOutStockInfo=newOutStockInfo.replace(/temp/g,num);

	$("#outStockInfo").append(newOutStockInfo);
	stocksShow(num);
	indexChange();
}

function deleteData(deleteId){
	if(index!=3){
		$("#"+deleteId).remove();
		updateBillingMoney();
		indexChange();
	}

}
var index;
function indexChange(){
	index=1;
	$("td[name='index']").each(function(){
		$(this).html(index);	
		index++;
	});
}
function saveData(lBtn){
	var isRepetition = false;
	var collocationIds=[];
	$("input[name='collocationId']").each(function(){
		collocationIds.push({
			id:$(this).val(),
			text:$(this).val()
		})
	});

	for(var i=0;i<collocationIds.length;i++){
		console.log(collocationIds[i].id);
		for(var j=i+1;j<collocationIds.length;j++){
			if(collocationIds[i].id!=""||collocationIds[j].id!=""){
				if(collocationIds[i].id==collocationIds[j].id){
					isRepetition=true;
				}
			}
			
		}
	}
	var isSave=false;
	$("input[name='collocationId']").each(function(){
		if($(this).val()!=null && $(this).val() != ""){
			isSave=true;
		}
						
	});
	if(!isSave){
		$.showTips("请选择开单货品！",1000,"warning");
		return;
	}

	if (!$("form:first").valid()){
		return;
	}
	lBtn.start();
	$("form:first").submit();
}	

function billing(lBtn){

	var isSave=false;
	$("input[name='collocationId']").each(function(){
		if($(this).val()!=null && $(this).val() != ""){
			isSave=true;
		}
						
	});
	if(!isSave){
		$.showTips("请选择开单货品！",1000,"warning");
		return;
	}
    var url=$("#billing").attr("action");
    url+="&mode=2";
    $("#billing").attr("action",url);
	if (!$("form:first").valid()){
		return;
	}
	lBtn.start();
	$("form:first").submit();
}
function iframeLazyOpen(){
	$(".nav.nav-tabs.nav-tabs-component li a").click(function(){
		var iframeTab = $(this).attr("href");
		var iframeId = iframeTab.substring(0,iframeTab.indexOf("-")) + "Iframe";
		$(iframeId).attr("src",$(iframeId).attr("data-src"));
	});
}

function tabpaneResize(){
	$(".tab-pane").height($(window).height() - 50);
	
	$(window).bind("resize",function(){$(".tab-pane").height($(window).height() - 50)});
	
}

function checkCustomer(){
	var customerId=$("#customerId").find("option:selected").val();	
	if($.isNull(customerId)){		
		$.showTips("请选择客户！",1000,"warning");
		return;
	}
}

function ValidateNumber(e, pnumber){
	if (!/^\d+[.]?\d*$/.test(pnumber))
	{
	e.value = /^\d+(\.\d+)?$/.exec(e.value);
	}else{
		
 	}
	return false;
}

function actionResultCallBack(){
	var result={close:true,refresh:false};
	var mode='${mode}';
	console.log(mode);
	if(mode=='2'){
		top.openModal("/billing/billing/addDetailed?type="+"add","billing1_form","订单详情-添加",1100,550);
	}else{
		top.main.formSubmit();
	}
	
	return result;
}
</script>
<%@ include file="/WEB-INF/views/shared/base/scripts/jqueryui.jsp"%>
<%@ include file="/WEB-INF/views/shared/base/scripts/limitless/default/formtags.jsp"%>
<%@ include file="/WEB-INF/views/shared/base/scripts/limitless/default/formbuttons.jsp"%>
<%@ include file="/WEB-INF/views/shared/base/scripts/limitless/default/formpickers.jsp"%>
<%@ include file="/WEB-INF/views/shared/base/scripts/limitless/default/formselects.jsp"%>
<%@ include file="/WEB-INF/views/shared/base/scripts/limitless/default/formstyling.jsp"%>
<%@ include file="/WEB-INF/views/shared/master/dialog.jsp"%>
<%@ include file="/WEB-INF/views/shared/master/contentFooter.jsp"%>